package action;

import java.io.IOException;
import java.text.ParseException;
import java.util.GregorianCalendar;
import java.util.Locale;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.hibernate.SessionFactory;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import domain.User;
import form.UserForm;

@Controller
@RequestMapping("print")
public class KorisnikAction {

	private Logger LOGGER = Logger.getLogger(this.getClass());

	private Validator validator;

	private SessionFactory sessionFactory;


	private GregorianCalendar cal;

	@RequestMapping("input")
	public ModelAndView unos() throws SchedulerException {

		ModelAndView mav = new ModelAndView("unosKorisnika");
		cal = new GregorianCalendar(new Locale("hr_HR"));
		String date = cal.getTime().toString();
		LOGGER.info("unosKorisnika");
		mav.addObject("date", date);
		mav.addObject("userForm", new UserForm());
		return mav;
	}

	@RequestMapping("submit")
	public ModelAndView prihvati(@ModelAttribute("userForm") UserForm userForm, BindingResult result, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ModelAndView mav = null;
		validator.validate(userForm, result);
		if (result.hasErrors()) {
			mav = new ModelAndView("unosKorisnika");
			return mav;
		}
		mav = new ModelAndView("ispisKorisnika");
		mav.addObject("userForm", userForm);
		mav.addObject("date", cal.getTime().toString());
		return mav;
	}

	@RequestMapping("persist")
	@Transactional
	public ModelAndView persist(@ModelAttribute("userForm") UserForm userForm, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, ParseException {
		
		User user = userForm.fetchDomainObject();
		sessionFactory.getCurrentSession().save(user);
		ModelAndView mav = null;
		mav = new ModelAndView("persistKorisnika");
		mav.addObject("userForm", userForm);
		mav.addObject("date", cal.getTime().toString());
		return mav;
	}

	@Autowired
	public void setValidator(Validator validator) {
		this.validator = validator;
	}

	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}


}
